//
//  WHDataStoreTreeVC.m
//  WHPersonalData
//
//  Created by shengmeng chen on 2023/4/23.
//  Copyright © 2023 mac. All rights reserved.
//

#import "WHDataStoreTreeVC.h"

@interface WHDataStoreTreeVC ()

@end

@implementation WHDataStoreTreeVC

-(instancetype)init
{
    self =[super init];
    if(self)
    {
        self.treeType = WHTreeTypeCustom;
        self.normalBackgroundColor =[UIColor whiteColor];
        self.rowHeight =45;
        //设置树字体
        NSArray *fontArr = @[[UIFont fontWithName:@"Helvetica-Bold" size:16],[UIFont fontWithName:@"Helvetica-Bold" size:14],[UIFont systemFontOfSize:14]];
        self.levelFontArray = fontArr;
    }
    return self;
}

-(instancetype)initWithTreeType:(WHTreeType)treeType
{
    self =[super init];
    if(self)
    {
        self.treeType = treeType;
        self.normalBackgroundColor =[UIColor whiteColor];
        self.rowHeight =45;
        //设置树字体
        NSArray *fontArr = @[[UIFont fontWithName:@"Helvetica-Bold" size:16],[UIFont fontWithName:@"Helvetica-Bold" size:14],[UIFont systemFontOfSize:14]];
        self.levelFontArray = fontArr;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.backgroundColor =[UIColor systemBackgroundColor] ;
    self.clearsSelectionOnViewWillAppear = NO;
}

#pragma mark - 测试数据

- (WHTreeManager *)getTreeDatasWtihType:(NSString*)type
{
    NSMutableSet *items = [NSMutableSet set];
    NSString *path = [[NSBundle mainBundle] pathForResource:type ofType:@"plist"];
    NSMutableArray* datas = [[NSMutableArray alloc]initWithContentsOfFile:path];
    
    // 第一级
    for (NSInteger i = 0; i < datas.count; i++)
    {
        NSDictionary *dict1  =datas[i];
        NSString * title1    =dict1[@"title"];
        NSArray * arr1       =dict1[@"arr"];
        
        WHTreeItem *level1 = [[WHTreeItem alloc] initWithName:title1
                                                           ID:[NSString stringWithFormat:@"1-%ld", i]
                                                     parentID:nil
                                                      orderNo:[NSString stringWithFormat:@"%lu", (unsigned long)i]
                                                         type:@"A"
                                                       isLeaf:NO
                                                         data:nil];
        [items addObject:level1];
        
        // 第二级
        for (NSInteger j = 0; j < arr1.count; j++)
        {
            NSDictionary *dict2  =arr1[j];
            NSString * title2    =dict2[@"title"];
            NSArray * arr2       =dict2[@"arr"];
            BOOL     isLeaf      =arr2.count>0?NO:YES;
            
            WHTreeItem *level2 = [[WHTreeItem alloc] initWithName:title2
                                                               ID:[NSString stringWithFormat:@"%@-%ld", level1.ID, j]
                                                         parentID:level1.ID
                                                          orderNo:[NSString stringWithFormat:@"%lu", (unsigned long)j]
                                                             type:@"A"
                                                           isLeaf:isLeaf
                                                             data:nil];
            [items addObject:level2];
            
            // 第三级
            for (NSInteger k = 0; k < arr2.count; k++)
            {
                NSString * title3    =arr2[k];
                WHTreeItem *level3 = [[WHTreeItem alloc] initWithName:title3
                                                                   ID:[NSString stringWithFormat:@"%@-%ld", level2.ID, k]
                                                             parentID:level2.ID
                                                              orderNo:[NSString stringWithFormat:@"%lu", (unsigned long)k]
                                                                 type:@"A"
                                                               isLeaf:YES
                                                                 data:nil];
                [items addObject:level3];
            }
        }
    }
    WHTreeManager *manager = [[WHTreeManager alloc] initWithItems:items andExpandLevel:0];
    
    return manager;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了第 %ld 行", (long)indexPath.row);
    
    WHTreeItem *item = (WHTreeItem *)self.manager.showItems[indexPath.row];
    
    // 折叠item的兄弟节点
    [self tableView:self.tableView willFoldBrotherItemWithSelectedItem:item];
    
    // 展开/折叠item节点
//    [self tableView:tableView didSelectItems:@[item] isExpand:!item.isExpand];
    
    [self tableView:self.tableView didSelectItems:@[item] isExpand:NO];
    [self tableView:self.tableView didSelectItems:@[item] isExpand:YES];
  
}

#pragma mark - Private Method

// 展开/折叠item节点
- (void)tableView:(UITableView *)tableView
   didSelectItems:(NSArray <WHTreeItem *>*)items
         isExpand:(BOOL)isExpand
{
    NSMutableArray *updateIndexPaths = [NSMutableArray array];
    NSMutableArray *editIndexPaths   = [NSMutableArray array];
    
    __block NSIndexPath *_selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    for (WHTreeItem *item in items)
    {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.manager.showItems indexOfObject:item] inSection:0];
        [updateIndexPaths addObject:indexPath];
        
        NSInteger updateNum = 0;
        if (isExpand)
        {
//            @weakify(self);
            if([item.type isEqualToString:@"AA"]){
                //AA：类型为AA的节点，选中自己并且只展开子节点不选中子节点
                updateNum = [self.manager expandItem:item];
                // 计算真正选中的哪一行
                [self tableView:tableView didChooseRowAtIndexPath:indexPath];
                _selectedIndexPath = indexPath;
            }else{
                updateNum = [self.manager expandItem:item andExpandFirstLevelChildItemByDeep:YES completed:^(WHTreeItem *lastItem, NSInteger itemIndex) {
    //                @strongify(self);
                    
                    _selectedIndexPath = [NSIndexPath indexPathForRow:itemIndex inSection:0];
                    WHTreeCell *cell = [self.tableView cellForRowAtIndexPath:_selectedIndexPath];
                    
                    NSLog(@"lastItem = %@", lastItem);
                    NSLog(@"itemIndex = %ld", itemIndex);
                    NSLog(@"cell = %@", cell);
                    
                    // 计算真正选中的哪一行
                    [self tableView:tableView didChooseRowAtIndexPath:_selectedIndexPath];
                    
                }];
            }
        }
        else
        {
            updateNum = [self.manager foldItem:item andFoldAllChildItems:YES];
        }
        
        NSArray *tmp = [self getUpdateIndexPathsWithCurrentIndexPath:indexPath andUpdateNum:updateNum];
        [editIndexPaths addObjectsFromArray:tmp];
    }
    
    if (self.isShowExpandedAnimation)
    {
        if (isExpand)
        {
            [tableView insertRowsAtIndexPaths:editIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        else
        {
            [tableView deleteRowsAtIndexPaths:editIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
        }
    }
    else
    {
        [tableView reloadData];
//        [self.tableView layoutIfNeeded];
        
        [tableView selectRowAtIndexPath:_selectedIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    }
    
    for (NSIndexPath *indexPath in updateIndexPaths)
    {
        WHTreeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell updateItem];
    }
}


// 折叠item的兄弟节点
- (void)tableView:(UITableView *)tableView willFoldBrotherItemWithSelectedItem:(WHTreeItem *)selectedItem
{
    WHTreeItem *parentItem = (WHTreeItem *)selectedItem.parentItem;
    NSArray *items = parentItem != nil ? parentItem.childItems : self.manager.topItems;
    
    for (WHTreeItem *item in items)
    {
        // 由于是兄弟节点展开互斥，所以items中的item只有一个是isExpand的
        if (item.isExpand && ![item isEqual:selectedItem])
        {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.manager.showItems indexOfObject:item] inSection:0];
            NSInteger updateNum = [self.manager foldItem:item andFoldAllChildItems:YES];
            NSArray *editIndexPaths = [self getUpdateIndexPathsWithCurrentIndexPath:indexPath andUpdateNum:updateNum];
            
            if (self.isShowExpandedAnimation)
            {
                [tableView deleteRowsAtIndexPaths:editIndexPaths withRowAnimation:UITableViewRowAnimationNone];
            }
            else
            {
                [tableView reloadData];
            }
            
            WHTreeCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            [cell updateItem];
        }
    }
}

// 计算真正选中的哪一行
- (void)tableView:(UITableView *)tableView didChooseRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"选中了第 %ld 行", (long)indexPath.row);

    WHTreeItem *item = (WHTreeItem *)self.manager.showItems[indexPath.row];
    if (self.outlineSelectPageBlock)
    {
        self.outlineSelectPageBlock(item,indexPath);
    }
}

-(void)setDefaultSelectFirsCell
{
    // 默认展开第二级节点
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.manager.allItems.count > 0)
        {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
        }
    });
}

- (void)expandItem:(WHTreeItem *)item
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.manager.allItems.count > 0)
        {
            [self.manager expandAnyItem:item];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.manager.showItems indexOfObject:item] inSection:0];
            [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
        }
    });
}



@end
